package com.cloudwise.gproject.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.cloudwise.gproject.entity.Visit;
import com.cloudwise.gproject.dao.VisitDao;
import com.cloudwise.gproject.listener.DataListener;
import com.cloudwise.gproject.service.VisitService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * (Visit)表服务实现类
 *
 * @author makejava
 * @since 2021-03-23 18:59:06
 */
@Service("visitService")
public class VisitServiceImpl implements VisitService {
    @Resource
    private VisitDao visitDao;
    @Resource
    private HttpServletResponse response;

    /**
     * 通过ID查询单条数据
     *
     * @param visitId 主键
     * @return 实例对象
     */
    @Override
    public Visit queryById(Integer visitId) {
        return this.visitDao.queryById(visitId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Visit> queryAllByLimit(int offset, int limit) {
        return this.visitDao.queryAllByLimit(offset, limit);
    }

    @Override
    public PageInfo queryAll(Integer page, Integer limit, Visit visit) {
        //设值查询查询
        PageHelper.startPage(page,limit);
        PageInfo PageInfo = new PageInfo(visitDao.queryAll(visit));
        return PageInfo;
    }


    /**
     * 新增数据
     *
     * @param visit 实例对象
     * @return 实例对象
     */
    @Override
    public Visit insert(Visit visit) {
        this.visitDao.insert(visit);
        return visit;
    }

    /**
     * 修改数据
     *
     * @param visit 实例对象
     * @return 实例对象
     */
    @Override
    public Visit update(Visit visit) {
        this.visitDao.update(visit);
        return this.queryById(visit.getVisitId());
    }

    /**
     * 通过主键删除数据
     *
     * @param visitId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer visitId) {
        return this.visitDao.deleteById(visitId) > 0;
    }

    @Override
    public int deleteIds(String deleteIds) {
        return 0;
    }

    @Override
    public boolean importVisit(MultipartFile file) {
        ExcelReader excelReader = null;
        try {
            //实例化监听对象
            DataListener dataListener =new DataListener();
            //读excel数据到excelReader对象中
            excelReader = EasyExcel.read(file.getInputStream(), Visit.class,dataListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            //定义标识符
            boolean isSuc =true;
            //获取读取到的数据列表
            List list =  dataListener.getList();
            //判断是否为空
            if(!CollectionUtils.isEmpty(list)){
                //循环对象
                for (Object o : list) {
                    Visit visit =(Visit) o;
                    Visit returnCustom = this.insert(visit);
                    if(returnCustom==null){
                        isSuc=false;
                    }
                }
            }
            return isSuc;
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return false;
    }

    @Override
    public boolean exportVisit(Visit visit) {
        ExcelWriter excelWriter = null;
        try {
            OutputStream outputStream = response.getOutputStream();
            //设值导出内容的类型及编码方式
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //设值头部信息，主要设值导出文件名称
            response.setHeader("Content-disposition","attachment;filename="+System.currentTimeMillis()+".xlsx");
            List<Visit> customList = visitDao.queryAll(visit);
            excelWriter = EasyExcel.write(outputStream, Visit.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("客户信息").build();
            excelWriter.write(customList, writeSheet);
            return  true;
        }catch (Exception e){
            e.printStackTrace();
        } finally{
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        return false;
    }

    @Override
    public Map<String, Object> visitEchartTime(String loginName) {
        List<Map<String, Object>> maps = visitDao.visitEchartTime(loginName);
        Map<String, Object> map = new HashMap<>();
        //定义x轴
        String[] monthX = new String[maps.size()];
        //定义y轴
        Integer[] visitCountY = new Integer[maps.size()];
        for (int i = 0; i < maps.size(); i++) {
            monthX[i] = maps.get(i).get("month").toString();
            visitCountY[i] = Integer.parseInt(maps.get(i).get("visit_count").toString());
        }
        map.put("monthX", monthX);
        map.put("visitCountY", visitCountY);
        return map;
    }

    @Override
    public Map<String, Object> visitEchartName(String startTime, String endTime) {
        List<Map<String, Object>> maps = visitDao.visitEchartName(startTime, endTime);
        Map<String, Object> map = new HashMap<>();
        //定义x轴
        String[] loginNameX = new String[maps.size()];
        //定义y轴
        Integer[] visitCountY = new Integer[maps.size()];
        for (int i = 0; i < maps.size(); i++) {
            loginNameX[i] = maps.get(i).get("login_name").toString();
            visitCountY[i] = Integer.parseInt(maps.get(i).get("visit_count").toString());
        }
        map.put("loginNameX", loginNameX);
        map.put("visitCountY", visitCountY);
        return map;
    }


}
